package com.framework.foundation.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;

import com.framework.foundation.common.Constant;
import com.framework.foundation.common.ConstantResult;
import com.framework.foundation.common.vo.Result;
import com.framework.foundation.system.user.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;

/**
 * 后台拦截器
 * 
 * @Author: Brin
 * @Date: 2015年10月21日 上午11:17:28
 */
public class AdminInterceptor implements Interceptor {

	protected static final Log LOG = Log.getLog(AdminInterceptor.class);

	/**
	 * 需要拦截的url
	 */
	private String urlPattern;

	/**
	 * 授权不拦截的地址
	 */
	private String[] allowUrls;

	public AdminInterceptor(String urlPattern) {
		this.urlPattern = urlPattern;
	}

	/**
	 * 
	 * constructor
	 * 
	 * @param urlPattern 需要拦截的地址
	 * @param allowUrls 授权不拦截的地址
	 * @Author: Brin
	 * @Date: 2015年10月21日 下午1:18:24
	 */
	public AdminInterceptor(String urlPattern, String[] allowUrls) {
		this.urlPattern = urlPattern;
		this.allowUrls = allowUrls;
	}

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		HttpServletRequest request = controller.getRequest();
		HttpServletResponse response = controller.getResponse();

		final String actionKey = inv.getActionKey();

		boolean result = false;
		if (ArrayUtils.isNotEmpty(allowUrls)) {
			// /判断是否为拦截的路径,不为拦截的路径直接通过
			result = CollectionUtils.exists(Arrays.asList(allowUrls), new Predicate() {
				@Override
				public boolean evaluate(Object input) {
					return StringUtils.contains(actionKey, (String) input);
				}
			});
		}

		if (!result) {
			// 只处理需要拦截的路径
			if (actionKey.startsWith(urlPattern)) {
				User user = controller.getSessionAttr(Constant.ADMIN_USER);
				if (user != null) {
					controller.setSessionAttr(Constant.ADMIN_USER, user);
					// 测试权限异常
					// if (actionKey.equals("/admin/role/roleUser")) {
					// if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {// 不是ajax请求
					//
					// } else {// ajax请求session超时处理
					// try {
					// response.setHeader("redirectUrl",
					// "/admin/error?msg=" + URLEncoder.encode("抱歉,您没有权限访问该模块", "UTF-8"));
					// } catch (UnsupportedEncodingException e) {
					// e.printStackTrace();
					// }
					// }
					// return;
					// }
				} else {
					if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {// 不是ajax请求
						controller.redirect("/login");
					} else {// ajax请求session超时处理
						response.setHeader("redirectUrl", "/login");
					}
					return;
				}
			}
		}

		try {
			inv.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {// 不是ajax请求
				try {
					controller.redirect("/error?msg=" + URLEncoder.encode(e.getMessage(), "UTF-8"));
				} catch (UnsupportedEncodingException e2) {
					e2.printStackTrace();
				}
			} else {// ajax请求session超时处理
				controller.renderJson(Result.create(ConstantResult.SERVER_CODE));
			}
		}

	}
}
